<?php
$PageSecurity = 9;
include_once ('includes/session.inc');
set_time_limit(0);

$timeWait = 40000;
$excelType = 'Excel5'; // default Excel 2003 - Excel5,Excel2007
$isCanUpload = false;
$affectRecord = 0;
$failRecord = 0;
$fails = '-';
$content = array('Ca Sỹ', 'Đang cập nhật...', 'Đã import', 'hoàn thành', 'lỗi', 'dòng', 'Quá trình upload bị lỗi.', 'Vui lòng chọn loại tập tin (*.xls, *.xlsx).');

$sheetIndex = !isset($_REQUEST['SheetIndex']) ? 0 : $_REQUEST['SheetIndex'];
$startRow = !isset($_REQUEST['StartRow']) ? 2 : $_REQUEST['StartRow'];

$uploaddir = 'tmp/imported/';
$currDate = getdate();

if (file_exists($_FILES['fileupload']['tmp_name'])) {
	if ($_FILES['fileupload']['type'] == "application/vnd.ms-excel" || ($_FILES['fileupload']['type'] == "application/x-msexcel")) {
		$nameUploadFile = $currDate['0'].basename($_FILES['fileupload']['name']);
		$isCanUpload = true;
	} else if ($_FILES['fileupload']['type'] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
		$nameUploadFile = $currDate['0'].basename($_FILES['fileupload']['name']);
		$isCanUpload = true;
		$excelType = 'Excel2007';
	}
	if ($isCanUpload) {
		if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $uploaddir.$nameUploadFile)) {
			$ajaxProgress = new Api_Ajax();

			$objPHPExcel = new Api_Excel($nameUploadFile, $uploaddir, $excelType);
			$objPHPExcel->loadIOFactory();
			$objPHPExcel->setActiveSheet($sheetIndex);
			$numberRow = $objPHPExcel->getRowCount();
			$stt = 1;
			if(!isset($_SESSION['MaxObjectNumber'])){
				$ForceConfigReload = true;
				include($PathPrefix . 'includes/GetConfig.php');
			}
			for ($rowIndex = $startRow; $rowIndex <= $numberRow; $rowIndex++) {
				// time start importing a record
				$time_start = microtime_float();
				// cap nhat ca si phat sinh ma tu dong
				/*try{
					
					$name = trim($objPHPExcel->getCellByColumnAndRow(1, $rowIndex));
					$realname = trim($objPHPExcel->getCellByColumnAndRow(2, $rowIndex));
					$iscomposer = trim($objPHPExcel->getCellByColumnAndRow(3, $rowIndex));
					$company = trim($objPHPExcel->getCellByColumnAndRow(4, $rowIndex));
					$contract = trim($objPHPExcel->getCellByColumnAndRow(5, $rowIndex));
					$startdatecontract = excel_date(trim($objPHPExcel->getCellByColumnAndRow(6, $rowIndex)), 'm/d/Y');
					$enddatecontract = excel_date(trim($objPHPExcel->getCellByColumnAndRow(7, $rowIndex)), 'm/d/Y');

					$number = $stt;
					if((strlen($number) < $_SESSION['MaxObjectNumber']) && (strlen($number) > 0)){
						$lengthZero = $_SESSION['MaxObjectNumber'] - strlen($number);
						$number = str_repeat('0', $lengthZero).$number;
					}

					if (! empty($name)) {
						$ObjectDetails = array(
					'object_number' => "CS".$number,
					'object_name' => $name,
					'object_real_name' => $realname,
					'object_company' => $company,
					'object_type' => !empty($iscomposer)? 3 : 1,
					'created_date' => date('Y-m-d'),
					'created_by' => $_SESSION['UserID'],
					'updated_date' => date('Y-m-d'),
					'updated_by' => $_SESSION['UserID']
						);
						$Errors = _single('api/object')->InsertObject($ObjectDetails, $_SESSION['UserID'], $_SESSION['Password']);
						if(sizeof($Errors) == 0){
							$newSingerId = $_SESSION['LastInsertId'];
							$PartnerDetails = array(
					'object_id' => $newSingerId,
					'contract_number' => $contract,
					'contract_date' => $startdatecontract,
					'contract_end' => $enddatecontract,
					'created_date' => date('Y-m-d'),
					'created_by' => $_SESSION['UserID'],
					'updated_date' => date('Y-m-d'),
					'updated_by' => $_SESSION['UserID']
							);
							$newContractId = _single('api/contract')->InsertContract($PartnerDetails, $_SESSION['UserID'], $_SESSION['Password']);
							$affectRecord++;
						}else{
							$failRecord++;
							$fails .= $name.'-';
						}
					}
					$stt++;
				}catch (Exception $e) {
					echo 'Caught exception: ',  $e->getMessage(), "\n";
				}*/
				
				$number = trim($objPHPExcel->getCellByColumnAndRow(1, $rowIndex));
				$name = trim($objPHPExcel->getCellByColumnAndRow(2, $rowIndex));
				$realname = trim($objPHPExcel->getCellByColumnAndRow(3, $rowIndex));
				$iscomposer = trim($objPHPExcel->getCellByColumnAndRow(4, $rowIndex));
				$company = trim($objPHPExcel->getCellByColumnAndRow(5, $rowIndex));
				$address = trim($objPHPExcel->getCellByColumnAndRow(9, $rowIndex));
				$phone = trim($objPHPExcel->getCellByColumnAndRow(10, $rowIndex));
				$mobile = trim($objPHPExcel->getCellByColumnAndRow(11, $rowIndex));
				$email = trim($objPHPExcel->getCellByColumnAndRow(12, $rowIndex));
				$contract = trim($objPHPExcel->getCellByColumnAndRow(6, $rowIndex));
				$startdatecontract = $objPHPExcel->getCellByColumnAndRow(7, $rowIndex);
				$enddatecontract = $objPHPExcel->getCellByColumnAndRow(8, $rowIndex);
				if(!empty($startdatecontract) && !is_string($startdatecontract)){
					$startdatecontract = excel_date(trim($startdatecontract), 'm/d/Y');
				}else{
					$startdatecontract = trim($startdatecontract);
				}
				if(!empty($enddatecontract) && !is_string($enddatecontract)){
					$enddatecontract = excel_date(trim($enddatecontract), 'm/d/Y');
				}else{
					$enddatecontract = trim($enddatecontract);
				}

				if (!empty($number) && !empty($name)) {
					$ObjectDetails = array(
						'object_number' => $number,
						'object_name' => $name,
						'object_real_name' => $realname,
						'object_company' => $company,
						'object_address' => $address,
						'object_phone' => $phone,
						'object_mobile' => $mobile,
						'object_email' => $email,
						'object_type' => !empty($iscomposer)? 3 : 1,						
						'updated_date' => date('Y-m-d'),
						'updated_by' => $_SESSION['UserID']
					);
					$Object = _single('api/object')->GetObjectByNumber($number, $_SESSION['UserID'], $_SESSION['Password']);
					if(sizeof($Object) != 0){
						// da xuat hien trong database thi cap nhat
						$Result = _single('api/object')->ModifyObject($Object['object_id'], $ObjectDetails, $_SESSION['UserID'], $_SESSION['Password']);
						// chinh sua hop dong
						$ContractDetails = array(
							'object_id' => $Object['object_id'],
							'contract_number' => $contract,
							'contract_date' => $startdatecontract,
							'contract_end' => $enddatecontract,
							'contract_type' => 0,						
							'updated_date' => date('Y-m-d'),
							'updated_by' => $_SESSION['UserID']
						);
						if(isset($Object['contract_id']) && !empty($Object['contract_id'])){
							_single('api/contract')->ModifyContract($Object['contract_id'], $ContractDetails, $_SESSION['UserID'], $_SESSION['Password']);
						}else{
							$ContractDetails['created_date'] = date('Y-m-d');
							$ContractDetails['created_by'] = $_SESSION['UserID'];
							_single('api/contract')->InsertContract($ContractDetails, $_SESSION['UserID'], $_SESSION['Password']);
						}
					}else{
						$ObjectDetails['created_date'] = date('Y-m-d');
						$ObjectDetails['created_by'] = $_SESSION['UserID'];
						$Result = _single('api/object')->InsertObject($ObjectDetails, $_SESSION['UserID'], $_SESSION['Password']);
						if(!empty($contract)){
							$ContractDetails = array(
								'object_id' => $_SESSION['LastInsertId'],
								'contract_number' => $contract,
								'contract_date' => $startdatecontract,
								'contract_end' => $enddatecontract,
								'contract_type' => 0,
								'created_date' => date('Y-m-d'),
								'created_by' => $_SESSION['UserID'],
								'updated_date' => date('Y-m-d'),
								'updated_by' => $_SESSION['UserID']
							);
							_single('api/contract')->InsertContract($ContractDetails, $_SESSION['UserID'], $_SESSION['Password']);
						}
					}
					if(sizeof($Result) == 0){
						$affectRecord++;
					}else{
						$failRecord++;
						$fails .= $rowIndex.'-';
					}
				}else{
					$failRecord++;
					$fails .= $rowIndex.'-';
				}

				$msgTitle = "$content[0]: $number - $name";
				$ajaxProgress->advance(($rowIndex + 1) / $numberRow, "$content[1] $rowIndex/$numberRow", $msgTitle);
				// time delay
				$time_end = microtime_float();
				$time = ($time_end - $time_start) * 1000000; // convert second into milisecond
				if ($time < $timeWait)
				usleep($timeWait - $time);
			}
			$ajaxProgress = null;
			echo '{success:true, msg:'.json_encode(array('content'=>"$content[2] $content[3]: $affectRecord - $content[4] $content[5] : $failRecord $fails")).'}';
			exit;
		} else {
			echo '{success:false, msg:'.json_encode($_FILES['fileupload']['name']).'}';
			exit;
		}
	}
} else {
	echo '{success:false, msg:'.json_encode($_FILES['fileupload']['name'].' không tồn tại.').'}';
	exit;
}

function microtime_float() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float) $usec + (float) $sec);
}
?>
